package com.simplenix.nicasio.sys;

import com.simplenix.nicasio.def.Module;
import com.simplenix.nicasio.misc.AppException;
import com.simplenix.nicasio.misc.FileUtil;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author fronald
 */
public class ShutdownTaskManager {

	private static ShutdownTaskManager stm;

	private List<ShutdownTask> tasks;

	public static ShutdownTaskManager getInstance() throws AppException {
		if (stm == null) {
			stm = new ShutdownTaskManager();
		}
		return stm;
	}

	private ShutdownTaskManager() throws AppException {
		try {
			tasks = new ArrayList<ShutdownTask>();
			List<Module> modules = SystemDef.getInstance().getModules().getModulesList();
			for (Module module : modules) {
				String pkg = module.getBasePackage();
				List<String> classes = FileUtil.getClassList(pkg + ".shutdown");
				for (String className : classes) {
					Class c = Class.forName(className);
					ShutdownTask shutdownTask = (ShutdownTask) c.newInstance();
					this.tasks.add(shutdownTask);
				}
			}
		} catch (InstantiationException e) {
			throw new AppException(e);
		} catch (ClassNotFoundException e) {
			throw new AppException(e);
		} catch (IllegalAccessException e) {
			throw new AppException(e);
		}
	}

	public void executeAll() throws AppException {
		for (ShutdownTask task : this.tasks) {
			task.doShutdown();
		}
	}

}
